/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.motoo.codec;

import java.nio.channels.SocketChannel;
import java.util.LinkedList;

import com.google.code.motoo.core.IoBuffer;
import com.google.code.motoo.core.IoHandler;
import com.google.code.motoo.core.IoSession;
import com.google.code.motoo.filter.IoFilter.NextIoFilter;
import com.google.code.motoo.utils.IoSessionUtils;

/**
 * 
 * @author linfengqi
 * @version 1.0  May 11, 2009
 */
public class DefaultProtocolEncoderOutput implements ProtocolEncoderOutput {
	
	private final static ThreadLocal<LinkedList<Object>> queueLocal = new ThreadLocal<LinkedList<Object>>();
	
	private boolean keepAlive;
	
	public DefaultProtocolEncoderOutput(boolean keepAlive) {
		this.keepAlive = keepAlive;
	}
	
	public void write(IoBuffer message) throws Exception {
		/*IoSession session = IoSessionUtils.getThreadLocalIoSession();
		IoHandler ioHandler = session.getHandler();
		SocketChannel channel = session.getSocketChannel();
		
		if (channel != null && channel.isOpen()) {
			synchronized (channel) {
				channel.write(message.buf());
			}
		}
		session.setLastAccessTime();
		if (!keepAlive) {
			ioHandler.sessionClosed(session);
			session.close();
		}
		IoSessionUtils.clearThreadLocalIoSession();*/
		
		LinkedList<Object> queue = getQueue();
		queue.addFirst(message);
	}

	public void flash(NextIoFilter next, IoSession session) throws Exception {
		LinkedList<Object> queue = getQueue();
		while (!queue.isEmpty()) {
			Object message = queue.removeLast();
			next.messageSend(session, message);
		}
	}
	
	private static LinkedList<Object> getQueue() {
		LinkedList<Object> queue = queueLocal.get();
		if (queue == null) {
			queue = new LinkedList<Object>();
			queueLocal.set(queue);
		}
		return queue;
	}

}
